const query = require('../config/connection');

//获取购物车列表
async function getCardListService (ctx, params) {
  let sql = `select petgoods.GoodsImage,petgoods.Stock,petgoods.Title,petgoods.SaleAmount,goods_cart_item.* from goods_cart_item left join petgoods on goods_cart_item.GoodsId=petgoods.GoodsNo where goods_cart_item.UserId='${params.userId}'`;
  try {
    let data = await query(sql);
    ctx.body = {
      "success": true,
      "data": data
    };
  } catch (error) {
    ctx.body = {
      "success": false,
      "message": error
    };
  }
}
//加入购物车
async function addToCardService (ctx, params) {
  //查询sql 添加购物车前先检查购物车表是否已经有此商品，有的话就更新购物车中商品数量，
  //否则就在购物车表新增一条记录
  let sql = `select * from goods_cart_item where GoodsId = ${params.goodsId} and UserId='${params.userId}'`
  console.log("2222222")
  let data = await query(sql);
  console.log(data)
  //查询结果大于0 代表购物车表已经存在此商品，此时只需更新购物车商品数量 Quantity
  if (data.length > 0) {
    let quantity = data[0].Quantity || 0;
    await updateCardService(ctx, params, quantity)
  } else {
    await addCardService(ctx, params)
  }
}
//更新购物车数量
async function updateCardService (ctx, params, quantity) {
  let num = quantity ? (quantity + 1) : params.quantity;
  let sql = `update goods_cart_item set Quantity = ${num} where GoodsId=${params.goodsId} `
  try {
    let data = await query(sql);
    ctx.body = {
      "success": true,
      "data": data
    }
  } catch (error) {
    ctx.body = {
      "success": false,
      "message": error
    }
  }
}
//添加购物车
async function addCardService (ctx, params) {
  let param = [];
  let key = [];
  for (let item in params) {
    let value = "'" + params[item] + "'"
    param.push(value)
    key.push(item)
  }
  let sql = `insert into goods_cart_item (${key.join(",")}) values(${param.join(",")})`;
  try {
    let data = await query(sql);
    ctx.body = {
      "success": true,
      "data": data
    }
  } catch (error) {
    ctx.body = {
      "success": false,
      "message": error
    }
  }
};

//删除购物车数据
async function delCartService (ctx, params) {
  let ids = params.ids;
  let sql = `delete from goods_cart_item where GoodsId in (${ids})`
  try {

    let data = await query(sql);
    ctx.body = {
      "success": true,
      "data": data
    };
  } catch (error) {
    ctx.body = {
      "success": false,
      "message": error
    };
  }
}
module.exports = {
  getCardListService,
  delCartService,
  addToCardService,
  updateCardService
}
